<template>
  <div>
    <el-drawer
      v-model="visible"
      title="起降点管理"
      :size="720"
      @closed="handleClose"
      class="route-points-draw"
    >
      <el-table
        :data="pointList"
        style="width: 100%"
        empty-text="暂无起降点"
        row-class-name="route-points-row"
        cell-class-name="route-points-cell"
        header-row-class-name="route-points-header"
      >
        <el-table-column prop="name" label="起降点名称" />
        <el-table-column prop="longitude" label="经度" align="right" />
        <el-table-column prop="latitude" label="纬度" align="right" />
        <el-table-column prop="altitude" label="高度" align="right" />
      </el-table>

      <template #footer>
        <div style="display: flex; justify-content: center">
          <el-button
            class="mt-4"
            style="width: 70%"
            @click="handleAddItem"
            type="primary"
          >
            新增
          </el-button>
        </div>
      </template>
    </el-drawer>

    <el-drawer
      v-model="formVisible"
      title="新增起降点"
      @closed="handleCloseForm"
      :size="910"
      class="points-drawer"
    >
      <el-tabs v-model="activeTab" @tab-click="handleClick">
        <el-tab-pane label="手工导入" name="manual">
          <el-form :inline="true" class="demo-form-inline">
            <el-row v-for="(item, index) in form" :key="index">
              <el-form-item label="起降点名称">
                <el-input
                  v-model="item.name"
                  placeholder="起降点名称"
                  clearable
                  style="width: 178px"
                />
              </el-form-item>
              <el-form-item label="经度">
                <el-input
                  v-model="item.longitude"
                  placeholder="经度"
                  clearable
                  style="width: 100px"
                />
              </el-form-item>
              <el-form-item label="纬度">
                <el-input
                  v-model="item.latitude"
                  placeholder="纬度"
                  clearable
                  style="width: 100px"
                />
              </el-form-item>
              <el-form-item label="高度">
                <el-col :span="19">
                  <el-input
                    v-model="item.altitude"
                    placeholder="高度"
                    clearable
                    style="width: 100px"
                  />
                </el-col>
                <el-col :span="1"></el-col>
                <el-col :span="4" class="text-center">
                  <el-button @click="handleDelete(index)">删除</el-button>
                </el-col>
              </el-form-item>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-button type="primary" @click="handleCreate">新增</el-button>
              </el-col>
            </el-row>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="文件导入" name="file">
          <el-upload
            ref="importExcelRef"
            drag
            action=""
            :limit="1"
            :show-file-list="false"
            :http-request="httpExcelRequest"
          >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
              拖拽文件到此处或 <em>点击上传</em>
            </div>
          </el-upload>
          <el-table
            :data="excelList"
            style="width: 100%"
            v-if="excelList.length > 0"
          >
            <el-table-column prop="name" label="起降点名称" />
            <el-table-column prop="longitude" label="经度" align="right" />
            <el-table-column prop="latitude" label="纬度" align="right" />
            <el-table-column prop="altitude" label="高度" align="right" />
            <el-table-column label="操作" align="center">
              <template #default="scope">
                <el-button
                  link
                  type="primary"
                  size="small"
                  @click.prevent="handleDeleteExcelList(scope.$index)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
      <template #footer>
        <div style="flex: auto">
          <el-button type="primary" @click="handleSave">保存</el-button>
          <el-button @click="handleCloseForm">关闭</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>
<script setup>
import { ref, reactive, watch, toRefs, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { UploadFilled } from "@element-plus/icons-vue";
import * as xlsx from "xlsx";
import api from "@/api/route";

const props = defineProps({
  visible: Boolean,
});

const { visible } = toRefs(props);
const emits = defineEmits(["change"]);

const pointList = ref([]);
const activeTab = ref("manual");
const formVisible = ref(false);
const form = reactive([
  {
    name: "",
    longitude: "",
    latitude: "",
    altitude: "",
  },
]);
const importExcelRef = ref(null);
const excelList = ref([]);

const httpExcelRequest = async (op) => {
  let file = op.file;
  let dataBinary = await readFile(file);
  let workBook = xlsx.read(dataBinary, { type: "binary", cellDates: true });
  let workSheet = workBook.Sheets[workBook.SheetNames[0]];
  const excelData = xlsx.utils.sheet_to_json(workSheet, { header: 1 });
  excelList.value = [
    ...excelList.value,
    ...excelData
      .filter((item, i) => i > 0)
      .map((item) => {
        return {
          name: item[0],
          longitude: item[1],
          latitude: item[2],
          altitude: item[3],
        };
      }),
  ];
  importExcelRef.value.clearFiles();
};

const readFile = (file) => {
  return new Promise((resolve) => {
    let reader = new FileReader();
    reader.readAsBinaryString(file);
    reader.onload = (ev) => {
      resolve(ev.target.result);
    };
  });
};

const handleDeleteExcelList = (index) => {
  excelList.value.splice(index, 1);
};

const handleAddItem = () => {
  formVisible.value = true;
};

const handleCloseForm = () => {
  form.splice(0, form.length, {
    name: "",
    longitude: "",
    latitude: "",
    altitude: "",
  });
  formVisible.value = false;
  activeTab.value = "manual";
  excelList.value = [];
  importExcelRef.value.clearFiles();
};

const handleClose = () => {
  pointList.value = [];
  form.splice(0, form.length, {
    name: "",
    longitude: "",
    latitude: "",
    altitude: "",
  });
  emits("change", "routePoints");
};

const handleCreate = () => {
  form.push({
    name: "",
    longitude: "",
    latitude: "",
    altitude: "",
  });
};

const handleDelete = (index) => {
  form.splice(index, 1);
};

const handleClick = (tab, event) => {
  // console.log(tab, event)
};

const handleSave = async () => {
  if (activeTab.value === "manual") {
    if (
      form.some(
        (item) =>
          !item.name || !item.longitude || !item.latitude || !item.altitude
      )
    ) {
      ElMessage.error("请填写完整的起降点信息！");
      return false;
    }
  } else {
    if (excelList.value.length === 0) {
      ElMessage.error("请上传起降点文件！");
      return false;
    }
    if (
      excelList.value.some(
        (item) =>
          !item.name || !item.longitude || !item.latitude || !item.altitude
      )
    ) {
      ElMessage.error("起降点信息不完整！");
      return false;
    }
  }
  const params = activeTab.value === "manual" ? form : excelList.value;
  const result = await api.addPoints(params);
  if (result.code === 200) {
    ElMessage.success({
      context: result.msg,
      onClose: () => {
        pointList.value = [...pointList.value, ...result.data];
        handleCloseForm();
      },
    });
  } else {
    ElMessage.error(result.msg || "服务器忙，请稍后重试！");
  }
};

watch(visible, (newValue, oldValue) => {
  if (newValue) {
    getPointList();
  }
});

const getPointList = async () => {
  const result = await api.getPointList();
  if (result.code === 200) {
    pointList.value = result.data || [];
  } else {
    ElMessage.error(result.msg || "服务器忙，请稍后重试！");
  }
};
</script>

<style scoped lang="scss">
::v-deep .el-drawer__header {
  padding-top: 0;
  padding-right: 0;
  margin: 0;
}
::v-deep .route-points-draw {
  background: linear-gradient(
    180deg,
    rgba(8, 40, 75, 0.45) 0%,
    rgba(10, 41, 73, 0.45) 15.35%,
    rgba(11, 70, 146, 0.45) 35.16%,
    rgba(11, 78, 167, 0.45) 62.46%,
    rgba(11, 30, 60, 0.45) 83.98%,
    rgba(13, 33, 58, 0.45) 100%
  ) !important;
  border: 4px solid;
  border-color: rgba(84, 84, 84, 0.45);
  border-radius: 15px;
}
::v-deep .el-button--primary {
  // background: linear-gradient(
  //   180deg,
  //   rgba(8, 40, 75, 0.85) 0%,
  //   rgba(10, 41, 73, 0.85) 15.35%,
  //   rgba(11, 70, 146, 0.85) 35.16%,
  //   rgba(11, 78, 167, 0.85) 62.46%,
  //   rgba(11, 30, 60, 0.85) 83.98%,
  //   rgba(13, 33, 58, 0.85) 100%
  // ) !important;
}
</style>
